package model

import (
	"github.com/hajimehoshi/ebiten/v2"
	"time"
)

type Enemy struct {
	*Entity
	Enemies []*Enemy
}

const (
	enemyInterval = 2 * time.Second // 敌人生成间隔
)

var (
	lastEnemyTime time.Time // 上次生成敌人的时间
)

func NewEnemy(config *Config) *Enemy {
	path := "static/img/enemy.png"
	enemy := &Enemy{
		Entity:  NewEntity(path),
		Enemies: []*Enemy{},
	}
	enemy.X = float64(config.ScreenWidth)
	enemy.Y = float64(config.ScreenHeight - enemy.Height)
	return enemy
}

func (e *Enemy) CreateEnemy(config *Config) {
	// 更新敌人的位置并移除超出屏幕的敌人
	var updatedEnemies []*Enemy
	for _, enemy := range e.Enemies {
		enemy.X -= float64(config.BgSpeedFactor) * 3
		if enemy.X > -float64(enemy.Width) {
			updatedEnemies = append(updatedEnemies, enemy)
		}
	}
	e.Enemies = updatedEnemies
	currentTime := time.Now()

	// 生成敌人
	if len(e.Enemies) == 0 && currentTime.Sub(lastEnemyTime) >= enemyInterval {
		enemy := NewEnemy(config)
		e.Enemies = append(e.Enemies, enemy)
		lastEnemyTime = currentTime

	}

}

func (e *Enemy) Draw(screen *ebiten.Image) {
	// 绘制敌人
	for _, enemy := range e.Enemies {
		enemy.DrawScreen(screen)
	}
}
